package com.goxplanet;

import java.net.InetAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MarketDataService extends MarketDataPublisherGrpc.MarketDataPublisherImplBase{
    ExecutorService publisher = Executors.newFixedThreadPool(10);

    @Override
    public void query(com.goxplanet.Subscription request,
                      io.grpc.stub.StreamObserver<com.goxplanet.MarketData> responseObserver) {
        MarketData reply = MarketData.newBuilder()
                .setTicker(this.getTicker())
                .setPrice(1)
                .setExchangeRecvTime(System.nanoTime())
                .build();
        responseObserver.onNext(reply);
        responseObserver.onCompleted();
    }

    @Override
    public void subscribe(com.goxplanet.Subscription request,
                          io.grpc.stub.StreamObserver<com.goxplanet.MarketData> responseObserver) {
        publisher.submit(()->{
            while(true) {
                try {
                    MarketData reply = MarketData.newBuilder()
                            .setTicker(this.getTicker())
                            .setPrice(1)
                            .setExchangeRecvTime(System.nanoTime())
                            .build();
                    responseObserver.onNext(reply);
                    Thread.sleep(1000);
                }catch (Exception ex){
                    ex.printStackTrace();
                    break;
                }
            }
            responseObserver.onCompleted();
        });
    }

    private Ticker getTicker(){

        String host = "Unknown";
        try {
            host = InetAddress.getLocalHost().getHostName();
        }catch (Exception ex){
            ex.printStackTrace();
        }
        Ticker ticker = Ticker.newBuilder().setMarket(host).build();
        return ticker;
    }
}
